import json
import logging
import traceback

from django.http import HttpResponse
from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin

from App.models import User

login_list = ['/index/', '/addinfo/', '/personal/', '/personal/update_info/', '/personal/upload/resource/']


class MiddleWare(MiddlewareMixin):
    """用户登录中间件"""

    def process_request(self, request):
        target_url = request.get_full_path()
        if target_url in login_list:
            # 如果session数据符合登录要求，直接跳过登录
            user_id = request.session.get('userId')
            # if request.session:    WARN:request.session是一个对象而不是空字典，所以不可直接if。
            if User.objects.filter(userId=user_id):
                return
            # 若无session数据则跳转至登录界面
            else:
                return redirect('/?next={}'.format(target_url))

    """全局错误日志中间件"""

    def process_exception(self, request, exception):
        user_id = request.session.get('userId')
        username = User.objects.filter(userId=user_id).first().username
        logger_error = logging.getLogger('django')
        error_log = traceback.format_exc()
        error_msg = f"\n[username:{username}][except:{exception}],\ndetailed_info:{error_log}"
        logger_error.error(error_msg)
        return HttpResponse(json.dumps(dict(code=500, data={}, msg="Some thing error")),
                            content_type="application/json")
